package com.atguigu.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.vo.UserBindVO;
import com.atguigu.srb.core.service.UserBindService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author lwm
 * @since 2022-02-10
 */
@Api(tags = "会员账号绑定")
@RestController
@RequestMapping("/api/core/userBind")
@Slf4j
public class UserBindController {
    @Resource
    private UserBindService userBindService;

    @ApiOperation("绑定账户并生成表单字符串")
    @PostMapping("/auth/bind")
    public R bind(@RequestBody UserBindVO userBindVO, @RequestHeader String token){
        //校验token并获取uid
        Long userId = JwtUtils.getUserId(token);
        //生成表单数据
        String formStr = userBindService.genFormData(userBindVO,userId);
        return R.ok().data("formStr",formStr);
    }

    @ApiOperation("账户绑定的异步回调")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request){
        //获取所有参数并通过工具类转换
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("用户账号绑定异步回调：" + JSON.toJSONString(paramMap));
        //校验签名，将map里除sign参数外所有参数按约定的方式生成签名，
        // 将生成的sign和map中的sign比较
        if (!RequestHelper.isSignEquals(paramMap)){
            log.error("用户账号绑定异步回调签名错误：" + JSON.toJSONString(paramMap));
            //回调签名错误说明，给的sign有误，或者参数有误，被中途截取了，返回fail
            return "fail";
        };
        //修改绑定状态
        userBindService.updateBind(paramMap);
        return "success";
    }
}

